var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var od_number = $("#od_number").val();
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var queryurl = config.BASEPATH+'batch/order/detail_list/'+od_number;
var querysumurl = config.BASEPATH+'batch/order/detail_sum/'+od_number;
var querysizeurl = config.BASEPATH+'batch/order/detail_size/'+od_number;
var querysizetitleurl = config.BASEPATH+'batch/order/detail_size_title/'+od_number;

var needListRefresh = false;//列表模式
var needSizeRefresh = false;//尺码模式
var needSumRefresh = false;//汇总模式
var _height = $(parent).height()-278,_width = $(parent).width()-2;
var showMode = {
	display:function(mode){
		$("#CurrentMode").val(mode);
		$("a[name='mode-btn']").removeClass("on");
		$("#list-grid").hide();
		$("#size-grid").hide();
		$("#sum-grid").hide();
		if(mode == 0){
			$("#listBtn").addClass("on");
			$("#list-grid").show();
			showMode.refreshList();
		}else if(mode == 1){
			$("#sizeBtn").addClass("on");
			$("#size-grid").show();
			showMode.refreshSize();
		}else if(mode == 2){
			$("#sumBtn").addClass("on");
			$("#sum-grid").show();
			showMode.refreshSum();
		}
	},
	refreshList:function(){//列表模式刷新数据
		if(!needListRefresh){
    		return;
    	}
    	THISPAGE.reloadGridData();
    	needListRefresh = false;
	},
	refreshSum:function(){
		if(!needSumRefresh){
			return;
		}
		$('#sumGrid').GridUnload();
		THISPAGE.addEvent();
		THISPAGE.initSumGrid();
		needSumRefresh = false;
	},
	refreshSize:function(){
		if(!needSizeRefresh){
			return;
		}
		$.ajax({
			type:"POST",
			url:querysizetitleurl,
			cache:false,
			dataType:"json",
            success: function (data) {
            	if(undefined != data && data.stat == 200){
                    var titles = data.data.titles;
                    var sizeCodeMap = data.data.sizeCodeMap;
                    $('#sizeGrid').GridUnload();
                    THISPAGE.initSizeGroupGrid(titles, sizeCodeMap);
                    THISPAGE.addEvent();
                    needSizeRefresh = false;
				}else{
					Public.tips({type: 1, content : data.message});
				}
            }
        });
	},
	refresh:function(){
		var currentMode = $("#CurrentMode").val();
    	if(currentMode == '0'){//列表模式
    		needListRefresh = true;
    		showMode.refreshList();
        	needSizeRefresh = true;
        	needSumRefresh = true;
    	}else if(currentMode == '1'){//尺码模式
    		needSizeRefresh = true;
    		showMode.refreshSize();
    		needListRefresh = true;
        	needSumRefresh = true;
    	}else if(currentMode == '2'){//汇总模式
    		needSumRefresh = true;
    		showMode.refreshSum();
    		needListRefresh = true;
        	needSizeRefresh = true;
    	}
	}
};

var handle = {
	approve:function(){
		commonDia = $.dialog({ 
		   	id:'approve_confirm',
		   	title:'审批页面',
		   	data:{},
		   	max: false,
		   	min: false,
		   	lock:true,
		   	width:300,
		   	height:200,
		   	drag: true,
		   	resize:false,
		   	content:'url:'+config.BASEPATH+'approve/to_confirm',
		   	fixed:false,
		   	close : function(){
		   		var ar_infos = commonDia.content.ar_infos;
		   		if(ar_infos != undefined){
		   			handle.doApprove(ar_infos);
		   		}
		   	}
	    });
	},
	doApprove:function(ar_infos){
		$("#btn-approve").attr("disabled",true);
		var params = "";
		params += "number="+$("#od_number").val();
		params += "&ar_state="+ar_infos.ar_state;
		params += "&ar_describe="+Public.encodeURI(ar_infos.ar_describe);
		$.ajax({
            type: "POST",
            url: config.BASEPATH+"batch/order/approve",
            data: params,
            cache:false,
			dataType:"json",
            success: function (data) {
            	if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '审核成功'});
					handle.loadData(data.data);
				}else{
					Public.tips({type: 1, content : data.message});
				}
				$("#btn-approve").attr("disabled",false);
            }
        });
	},
	stop:function(){
		$.dialog.confirm('确定要终止单据吗？', function(){
			$("#btn-stop").attr("disabled",true);
			var params = "";
			params += "number="+od_number;
			$.ajax({
	            type: "POST",
	            url: config.BASEPATH+"batch/order/stop",
	            data: params,
	            cache:false,
				dataType:"json",
	            success: function (data) {
	            	if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : "终止成功"});
						handle.loadStopData(data.data);
					}else{
						Public.tips({type: 1, content : data.message});
					}
					$("#btn-stop").attr("disabled",false);
	            }
	        });
		});
	},
	loadData:function(data){
		var pdata = {};
		pdata.id=data.od_id;
		pdata.od_number=data.od_number;
		pdata.od_ar_state=data.od_ar_state;
		pdata.od_ar_date=data.od_ar_date;
		pdata.od_ar_name=data.od_ar_name;
		pdata.od_state=data.od_state;
		pdata.operate='';
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	loadStopData:function(data){
		var pdata = {};
		pdata.id=data.od_id;
		pdata.od_number=data.od_number;
		pdata.od_ar_state=data.od_ar_state;
		pdata.od_state=data.od_state;
		pdata.operate='';
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	doPrint:function(){
		var CurrentMode = $("#CurrentMode").val();
		var number = $("#od_number").val();
		$.dialog({ 
		   	id:'print_model_select',
		   	title:'单据打印模板',
		   	data:{'displayMode':CurrentMode,'number':number},
		   	max: false,
		   	min: false,
		   	lock:true,
		   	width:350,
		   	height:300,
		   	fixed:false,
		   	resize:false,
		   	content:'url:'+config.BASEPATH+'sys/print/to_list/3'
	    });
	},
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-image" title="图片">&#xe654;</i>';
		html_con += '</div>';
		return html_con;
	},
	formatGift :function(val, opt, row){
		if(row.odl_pi_type == 1){
			return '赠品';
		}
		return '';
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.addEvent();
		this.initGrid();
		this.initEvent();
	},
	initDom:function(){
		needListRefresh = false;//列表模式
        needSizeRefresh = true;//尺码模式
        needSumRefresh = true;//汇总模式
        var od_ar_state = $("#od_ar_state").val();
        var od_state = $("#od_state").val();
        if('approve' == api.data.oper){
			$("#btn-approve").show();
		}
        if('stop' == api.data.oper){
        	$("#btn-stop").show();
        }
	},
	gridTotal:function(){
    	var grid=$('#grid');
		var odl_amount=grid.getCol('odl_amount',false,'sum');
    	var odl_unitmoney=grid.getCol('odl_unitmoney',false,'sum');
    	var odl_costmoney=grid.getCol('odl_costmoney',false,'sum');
    	var odl_retailmoney=grid.getCol('odl_retailmoney',false,'sum');
    	grid.footerData('set',{odl_amount:odl_amount,odl_unitmoney:odl_unitmoney,odl_costmoney:odl_costmoney,odl_retailmoney:odl_retailmoney});
    	$("#od_amount").val(odl_amount);
    	$("#od_money").val(PriceLimit.formatByBatch(odl_unitmoney));
    },
    sumGridTotal:function(){
    	var grid=$('#sumGrid');
    	var odl_amount=grid.getCol('odl_amount',false,'sum');
    	var odl_unitmoney=grid.getCol('odl_unitmoney',false,'sum');
    	var odl_costmoney=grid.getCol('odl_costmoney',false,'sum');
    	var odl_retailmoney=grid.getCol('odl_retailmoney',false,'sum');
    	grid.footerData('set',{odl_amount:odl_amount,odl_unitmoney:odl_unitmoney,odl_costmoney:odl_costmoney,odl_retailmoney:odl_retailmoney});
    	$("#od_amount").val(odl_amount);
    	$("#od_money").val(PriceLimit.formatByBatch(odl_unitmoney));
    },
	initGrid:function(){
		var colModel = [
		    {label:'操作',name:'operate', width: 40, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
		    {label:'',name: 'odl_pd_code', index: 'odl_pd_code', hidden:true},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'颜色',name: 'cr_name', index: 'cr_name', width: 60},
	    	{label:'尺码',name: 'sz_name', index: 'sz_name', width: 60},
	    	{label:'杯型',name: 'br_name', index: 'br_name', width: 60},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60},
	    	{label:'数量',name: 'odl_amount', index: 'odl_amount', width: 70,align:'right',sorttype: 'int',editable:true},
	    	{label:'批发价',name: 'odl_unitprice', index: 'odl_unitprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByBatch},
	    	{label:'批发金额',name: 'odl_unitmoney', index: 'odl_unitmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByBatch},
	    	{label:'成本价',name: 'odl_costprice', index: 'odl_costprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'成本金额',name: 'odl_costmoney', index: 'odl_costmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'零售价',name: 'odl_retailprice', index: 'odl_retailprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'零售金额',name: 'odl_retailmoney', index: 'odl_retailmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'赠品',name: 'gift', index: 'odl_pi_type', width: 60,align:'center',formatter: handle.formatGift},
	    	{label:'',name: 'odl_pi_type', index: 'odl_pi_type', width: 100,hidden:true},
	    	{label:'折扣率',name: 'odl_rate', index: 'odl_rate', width: 70,align:'right',sorttype: 'int',formatter: PriceLimit.formatByBatch_Sell},
	    	{label:'备注',name: 'odl_remark', index: 'odl_remark', width: 180}
	    ];
		$('#grid').jqGrid({
			url:queryurl,
			loadonce:true,
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:false,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'odl_id'  //图标ID
			},
			loadComplete: function(data){
				var ids = $("#grid").getDataIDs();
				THISPAGE.gridTotal();
			},
			loadError: function(xhr, status, error){		
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
				
			}
	    });
	},
	initSumGrid:function(){
		var colModel = [
		    {label:'操作',name:'operate', width: 40, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
		    {label:'',name: 'odl_pd_code', index: 'odl_pd_code', hidden:true},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'品牌',name: 'bd_name', index: 'pd_bd_code', width: 80},
	    	{label:'类别',name: 'tp_name', index: 'pd_tp_code', width: 80},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60},
	    	{label:'数量',name: 'odl_amount', index: 'odl_amount', width: 70,align:'right',sorttype: 'int'},
	    	{label:'批发价',name: 'odl_unitprice', index: 'odl_unitprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByBatch},
	    	{label:'批发金额',name: 'odl_unitmoney', index: 'odl_unitmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByBatch},
	    	{label:'成本价',name: 'odl_costprice', index: 'odl_costprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'成本金额',name: 'odl_costmoney', index: 'odl_costmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'零售价',name: 'odl_retailprice', index: 'odl_retailprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'零售金额',name: 'odl_retailmoney', index: 'odl_retailmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'赠品',name: 'gift', index: 'odl_pi_type', width: 60,align:'center',formatter: handle.formatGift},
	    	{label:'',name: 'odl_pi_type', index: 'odl_pi_type', width: 100,hidden:true},
	    	{label:'折扣率',name: 'odl_rate', index: 'odl_rate', width: 70,align:'right',sorttype: 'int',formatter: PriceLimit.formatByBatch_Sell},
	    	{label:'备注',name: 'odl_remark', index: 'odl_remark', width: 180}
	    ];
		$('#sumGrid').jqGrid({
			url:querysumurl,
			loadonce:true,
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#sumPage',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:false,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'odl_id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.sumGridTotal();
			},
			loadError: function(xhr, status, error){		
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
			}
	    });
	},
	initSizeGroupGrid:function(dyColNames, sizeCodeMap) {
		var gridWH = Public.setGrid();//操作
        var headers = [];
        var dyns = dyColNames;
        var dySize = dyns.length;
        var dms = [];
        for (var i = 0; i < dyns.length; i++) {
            var dys = dyns[i];
            for (var j = 0; j < dys.length; j++) {
                var dyss = null;
                dyss = dys[j].split('_AND_');
                if (i == 0 && j == 0) {
                    dyns[i][j] = dyss[0];
                }
                headers.push(dyss[1]);
                dms.push({label:dyss[1],name: dyss[0], index: dyss[0], width: 45, title: false, align: 'right', sorttype: 'int', sortable: false});
            }
            break;
        }
		var colModel = [
            {label:'',name: 'sizeGroupCode', hidden: true},
            {label:'',name: 'pd_code', index: 'pd_code', width: 100,hidden:true},
            {label:'',name: 'cr_code', index: 'cr_code', width: 100,hidden:true},
            {label:'',name: 'br_code', index: 'br_code', width: 100,hidden:true},
            {label:'操作',name:'operate', width: 40, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
            {label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'颜色',name: 'cr_name', index: 'odl_cr_code', width: 60},
	    	{label:'杯型',name: 'br_name', index: 'odl_br_code', width: 60},
        ];
        colModel = colModel.concat(dms);
        colModel = colModel.concat([
            {label:'数量',name: 'Amount_Total',	index:'Amount_Total',	width: 70, align: 'right', sorttype: 'int', sortable: false},
            {label:'批发价',name: 'unit_price', index: 'unit_price', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByBatch},
	    	{label:'批发金额',name: 'unit_money', index: 'unit_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByBatch},
	    	{label:'成本价',name: 'cost_price', index: 'cost_price', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'成本金额',name: 'cost_money', index: 'cost_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'零售价',name: 'retail_price', index: 'retail_price', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'零售金额',name: 'retail_money', index: 'retail_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'赠品',name: 'gift', index: 'gift', width: 60,align:'center',formatter: handle.formatGift},
	    	{label:'',name: 'odl_pi_type', index: 'odl_pi_type', width: 100,hidden:true}
	    ]);
        $('#sizeGrid').jqGrid({
			url: querysizeurl,
			loadonce:true,
            datatype: 'json',
            autowidth: true,
            height: gridWH.h-100,
            gridview: true,
            colModel: colModel,
            rownumbers: true,//行号
            pager: '#sizePage',//分页
            pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
            viewrecords: true,
            rowNum: 9999,//每页条数
            shrinkToFit: false,//表格是否自动填充
            footerrow: true,
            userDataOnFooter: true,
			jsonReader: {
				root: 'data.data',
				userdata: 'data.userData',
				repeatitems : false,
				id:'id'
			},
			loadComplete: function(data) {
				
			},
			gridComplete:function(){
				Public.resizeSpecifyGrid('sizeGrid', 215 + (dyns.length * 32), 2);
			},
			loadError: function(xhr, status, error) {
                Public.tips({type: 1, content : '操作失败了哦，服务可能已过期，请按F5刷新！'});
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
			},
			onPaging: function(pgButton) {
				
			},
            onSelectRow: function (rowId, status) {
                var sizeG = $("#sizeGrid").jqGrid("getRowData", rowId).sizeGroupCode;
                var bg = $('[sizeGCode=' + sizeG + ']').css("background");
                if (bg == 'none') {
                    return;
                }
                $("[sizeGCode]").css("background-color", '#eee');
                $('[sizeGCode=' + sizeG + ']').css({ "background": "none", "background-color": "#F8FF94"});
            }
	    });
        if (dySize >= 2) {
        	$('#sizeGrid').jqGrid('setGroupHeaders', {
                useColSpanStyle: true,
                groupHeaders:[]
            });
            $('#sizeGrid').jqGrid("setComplexGroupHeaders", {
                complexGroupHeaders: {startColumnName: dyns[0][0], numberOfColumns: dyns[0].length},
                rowspan: dySize,
                topTitle:true
            });
            for (var key in sizeCodeMap) {
                $('#sizeGrid').jqGrid("setComplexGroupHeaders",{
                    complexGroupHeaders: {startColumnName: dyns[0][0], numberOfColumns: dyns[0].length},
                    rowspan: dySize,
                    sizeGroupCode: key,
                    titleTextGroup:sizeCodeMap[key],
                    topTitle:false
                });
            }
        }else{
        	$('#sizeGrid').jqGrid('setGroupHeaders', {
                useColSpanStyle: true,
                groupHeaders: [{startColumnName: dyns[0][0], numberOfColumns: dyns[0].length, titleText: '尺码'}]
            });
        }
    },
	reloadGridData: function () {
        $("#grid").jqGrid('setGridParam', {datatype: 'json', page: 1, url: queryurl}).trigger("reloadGrid");
    },
	initEvent:function(){
		$('#btn-approve').on('click', function(e){
			e.preventDefault();
			handle.approve();
		});
		$('#btn-stop').on('click', function(e){
			e.preventDefault();
			handle.stop();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
        $('#grid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#grid").jqGrid("getRowData", id).odl_pd_code);
        });
	},
	addEvent:function(){
		//移除事件，防止重复绑定
		$('#sizeGrid').off('click','.operating .ui-icon-image');
		$('#sumGrid').off('click','.operating .ui-icon-image');
        $('#sizeGrid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#sizeGrid").jqGrid("getRowData", id).pd_code);
        });
        $('#sumGrid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#sumGrid").jqGrid("getRowData", id).odl_pd_code);
        });
	}
};

THISPAGE.init();